package com.it.ymcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.it.ymcc.entity.User;
import com.it.ymcc.entity.UserDto;
import com.it.ymcc.exception.BusinessException;
import com.it.ymcc.service.ILoginService;
import com.it.ymcc.service.IUserService;
import com.it.ymcc.utils.JwtUtils;
import com.it.ymcc.utils.Payload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public String loging(UserDto userDto) {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        Wrapper<User> userWrapper = new EntityWrapper<User>();
        userWrapper.eq("username",username);
        User user = userService.selectOne(userWrapper);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        if (!user.getPassword().equals(password)) {
            throw new BusinessException("密码错误");
        }
        //查询用户权限信息
        List<String> permissionList = userService.findPsById(user.getRoleId());
        System.out.println(permissionList);
        Payload payload = new Payload(user, permissionList);
        String jwt = JwtUtils.generateToken(payload);
        return jwt;
    }
}
